// wii libraries
#include <wiiuse/wpad.h>

// custom libraries
#include "..\include\logger.h"
#include "..\include\user_controller.h" // matching header


// ==================================
//    CONSTRUCTORS and DESTRCUTORS
// ==================================

UserController::UserController()
{
	initializeLibrary();

	buttonsPressed_ = 0;
	buttonsHeld_    = 0;
	buttonsUp_      = 0;
}

UserController::~UserController()
{
	exitLibrary();
}


// ==================================
//           BUTTON CHECK
// ==================================

// Array containing the actual values of the buttons on the controller. The 
// order in which the buttons are listed in the array is important: it should
// match the order in which the buttons are listed in the 
// UserController::Button enumeration.

u32 Buttons[UserController::BUTTON_LIST_SIZE] = {
	// The Wii Remote is meant to be held sideways so right is up, left is down, 
	// up is left, and down is right.
	WPAD_BUTTON_RIGHT, WPAD_BUTTON_LEFT, WPAD_BUTTON_UP, WPAD_BUTTON_DOWN,
	WPAD_BUTTON_2, WPAD_BUTTON_HOME 
};

void UserController::scanButtons()
{
	WPAD_ScanPads();
	buttonsPressed_ = (unsigned int)WPAD_ButtonsDown(0);
	buttonsHeld_    = (unsigned int)WPAD_ButtonsHeld(0);
	buttonsUp_      = (unsigned int)WPAD_ButtonsUp(0);
}

bool UserController::isButtonPressed(Button button)
{
	return (u32)buttonsPressed_ & Buttons[button];
}

bool UserController::isButtonHeld(Button button)
{
	return (u32)buttonsHeld_ & Buttons[button];
}

bool UserController::isButtonUp(Button button)
{
	return (u32)buttonsUp_ & Buttons[button];
}


// ==================================
//       INITIALIZE and EXIT
// ==================================

bool UserController::initializeLibrary()
{
	Logger::Instance()->addEntry(Logger::INFO, 
		"UserController: Initializing WPAD...");
	
	WPAD_Init();
	
	Logger::Instance()->addEntry(Logger::INFO, 
		"UserController: Initialization successful.");
	return true; // Cannot fail   
}

bool UserController::exitLibrary()
{
	Logger::Instance()->addEntry(Logger::INFO, 
		"UserController: Exiting WPAD...");
	
	// The current library does not require any function 
	// to be called upon exiting.
	
	Logger::Instance()->addEntry(Logger::INFO, 
		"UserController: Exit successful.");
	return true;
}
